Ext.define('appfe.stockor.statist.chart.KLineController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.stockor.statist.chart.KLine',
    // 十六进制到RGB颜色转换器 https://www.bchrt.com/tools/hex-to-rgb/
    bgColor: '#1f212d',//背景 0D0C0F
    upColor: 'rgba(249, 41, 62, 1)',//涨颜色 #F9293E rgb(249, 41, 62)
    upBorderColor: '#F9293E',
    downColor: '#54FFFF',//跌颜色 绿 #00aa3b rgb(0, 170, 59)  蓝 #54FFFF rgb(84, 255, 255)
    downBorderColor: '#54FFFF',

    // ma 颜色
    ma5Color: '#39afe6',/*蓝*/
    ma10Color: '#da6ee8',/*紫*/
    ma20Color: '#ffab42',/*橙黄*/
    ma30Color: '#00940b',/*绿*/
    /**
     * 点击查询按钮的查询方法
     */
    searchFn: function (button, clickEnven) {
        var me = this;
        var myview = me.getView();
        var myviewmodel = myview.getViewModel();
        var grade = myviewmodel.get('grade');
        // if (grade.length > 3) {
        //     Ext.MessageBox.alert('提示', '最多仅允许3个级别显示');
        //     return;
        // }
        var gradeUrlParam = '';
        for (var index in grade) {
            gradeUrlParam += '&grade=' + grade[index];
        }
        new_window_url = '' + window.location.origin + '?classic'
            + '&slimsymbol=' + myviewmodel.get('slimsymbol')
            + '&stkname=' + myviewmodel.get('stkname')
            + gradeUrlParam
            + '&klinetype=' + myviewmodel.get('klinetype')
            + '&isMacdDisplayed=' + myviewmodel.get('isMacdDisplayed')
            + (myviewmodel.get('klinetype') === 'standard' ? ('&keepIgnoredStdKline=' + myviewmodel.get('keepIgnoredStdKline')) : '')
            + '&_dc=' + new Date().getTime()
            + '#kline-window'
        //new Ext.util.DelayedTask(function () {
        window.location.href = new_window_url;
        //}).delay(5000);

    },
    onBoxReady: function () {
        var urlParamters = Ext.Object.fromQueryString(window.location.search)
        console.debug('urlParamters:', urlParamters);

        window.title = '查看K线-' + urlParamters.stkname;

        var me = this;
        var myview = me.getView();
        var myviewmodel = myview.getViewModel();

        var slimsymbol = urlParamters.slimsymbol;
        if (typeof (slimsymbol) === 'undefined' || slimsymbol == null || slimsymbol.trim() === '') {
            alert('URL参数:slimsymbol缺失');
            return;
        }

        me.verifySlimsymbol(myviewmodel, slimsymbol)
        if (!myviewmodel.get('isValidSlimsymbol')) {
            console.debug('myviewmodel:', myviewmodel);
            alert('URL参数:slimsymbol无效');
            return;
        }

        var klinetype = urlParamters.klinetype;
        if (typeof (klinetype) === 'undefined' || klinetype == null || klinetype.trim() === '') {
            alert('URL参数:klinetype缺失');
            return;
        } else if (klinetype != 'normal' && klinetype != 'standard' && klinetype != 'zinzen') {
            alert('URL参数:klinetype为非法值[normal, standard, zinzen]');
            return;
        } else {
            myviewmodel.set('klinetype', klinetype);
        }

        var isMacdDisplayed = urlParamters.isMacdDisplayed;
        if (typeof (isMacdDisplayed) === 'undefined' || isMacdDisplayed == null || isMacdDisplayed.trim() === '') {
            alert('URL参数:isMacdDisplayed缺失');
            return;
        } else if (isMacdDisplayed != 'true' && isMacdDisplayed != 'false') {
            alert('URL参数:isMacdDisplayed为非法值[true, false]');
            return;
        } else {
            myviewmodel.set('isMacdDisplayed', isMacdDisplayed === 'true' ? true : false);
        }

        var keepIgnoredStdKline = urlParamters.keepIgnoredStdKline;
        if (typeof (keepIgnoredStdKline) === 'undefined' || keepIgnoredStdKline == null || keepIgnoredStdKline.trim() === '') {
            myviewmodel.set('keepIgnoredStdKline', true);
        } else if (keepIgnoredStdKline != 'true' && keepIgnoredStdKline != 'false') {
            alert('URL参数:keepIgnoredStdKline为非法值[true, false]');
            return;
        } else {
            myviewmodel.set('keepIgnoredStdKline', keepIgnoredStdKline === 'true' ? true : false);
        }

        var grade = urlParamters.grade;
        if (typeof (grade) === 'undefined' || grade == null) {
            alert('URL参数:grade缺失');
            return;
        }
        if (!Ext.isArray(grade)) {
            grade = new Array(grade);
        }
        if (grade.lenght === 0) {
            alert('URL参数:grade缺失');
            return;
        }
        for (var index in grade) {
            if (!grade[index] === 'M01' && !grade[index] === 'M05' && !grade[index] === 'M30' && !grade[index] === 'DAY') {
                alert('URL参数:grade值非法[M01, M05, M30, DAY]');
                return;
            }
        }
        //将Grade参数按界别大小排序后设置到下拉框
        var gradeKeyArray = ['M01', 'M05', 'M30', 'DAY'];
        var newGradeArray = [];
        for (var idx in gradeKeyArray) {
            grade.forEach(function (value, index) {
                if (gradeKeyArray[idx] == value) {
                    newGradeArray.push(gradeKeyArray[idx]);
                }
            });
        }
        myviewmodel.set('grade', newGradeArray);

        me.drawKlineCharts();
    },


    onResize: function (me, width, height, oldWidth, oldHeight, eOpts) {
        var myview = this.getView();
        var myviewmodel = myview.getViewModel();
        var klineDayChart = myviewmodel.get('klineChartPanel');
        if (klineDayChart != null) {
            klineDayChart.resize();
        }
    },
    drawKlineCharts: function () {
        var myview = this.getView();
        var myviewmodel = myview.getViewModel();
        var slimsymbol = myviewmodel.get('slimsymbol');
        var stkname = myviewmodel.get('stkname');
        var klinetype = myviewmodel.get('klinetype');
        var isMacdDisplayed = myviewmodel.get('isMacdDisplayed');
        var keepIgnoredStdKline = myviewmodel.get('keepIgnoredStdKline');



        var kChart = echarts.init(myview.lookup('klineChartPanel').getEl().dom, null, { renderer: 'canvas' });
        kChart.showLoading();

        var myRawDatasMap = new Map();
        var grades = myviewmodel.get('grade');
        for (var index in grades) {
            var grade = grades[index];
            var rawData;
            Ext.Ajax.request({
                url: BizHttpAction.queryStandardKlineList.url + (local_ajax ? '_' + grade + '.json' : ''),
                params: {
                    slimsymbol: slimsymbol,
                    grade: grade,
                    klinetype: klinetype,
                    isMacdDisplayed: isMacdDisplayed,
                    keepIgnoredStdKline: keepIgnoredStdKline
                },
                method: BizHttpAction.queryStandardKlineList.method,
                async: false,
                success: function (response, opts) {
                    var respJson = Ext.JSON.decode(response.responseText);
                    if (respJson.success != true) {
                        Ext.MessageBox.alert('提示', respJson.message);
                        return;
                    }
                    rawData = respJson.data;
                },
                failure: function (response, opt) {
                    var respJson = Ext.JSON.decode(response.responseText);
                    Ext.MessageBox.alert('提示', respJson.message);
                }
            });

            myRawDatasMap.set(grade, rawData);
        }
        kChart.hideLoading();
        kChart.setOption(this.initKOption(myRawDatasMap, stkname + '-K线图表面板'));//initKOption是初始化图表面板的重要方法
        myviewmodel.set('klineChartPanel', kChart);
    },
    /**
     * 指定图表的配置项和数据  
     * @param {*} myRawDatasMap 
     * @returns 
     */
    initKOption: function (myRawDatasMap, title) {
        var me = this;
        var myview = me.getView();
        var myviewmodel = myview.getViewModel();
        var isMacdDisplayed = myviewmodel.get('isMacdDisplayed');

        var gradeKeyArray = ['M01', 'M05', 'M30', 'DAY'];
        var gradeArray = [];
        var klineDataArray = [];
        for (var index in gradeKeyArray) {
            var httpKlineData = myRawDatasMap.get(gradeKeyArray[index]);
            if (typeof (httpKlineData) === 'undefined' || httpKlineData == null) {
                continue;
            } else {
                gradeArray.push(gradeKeyArray[index]);
                var tmpData = me.splitData(httpKlineData.kline, isMacdDisplayed);
                klineDataArray.push(tmpData);
            }
        }

        const grids = [];
        const xAxes = [];
        const yAxes = [];
        const series = [];
        const titles = [];
        const xAxisIndexArray = [];


        console.log('gradeArray.length:', gradeArray.length);
        console.log('isMacdDisplayed:', isMacdDisplayed);

        var perGradeChartHight = ((87 - (gradeArray.length - 1) * 3) / gradeArray.length).toFixed(0);
        console.log('每个级别的高度:', perGradeChartHight);

        var perGradeKlineChartHight = 0, perGradeMACDChartHight = 0;
        if (isMacdDisplayed) {
            perGradeKlineChartHight = ((perGradeChartHight - 1) * 0.8).toFixed(0);
            perGradeMACDChartHight = ((perGradeChartHight - 1) * 0.2).toFixed(0);
            console.log('每个级别的K线高度:', perGradeKlineChartHight);
            console.log('每个级别的M线高度:', perGradeMACDChartHight);
        } else {
            perGradeKlineChartHight = perGradeChartHight;
            console.log('每个级别的K线高度:', perGradeKlineChartHight);
        }

        var startPosition = 5, gridCount = 0;
        for (var index in gradeArray) {
            console.log('级别：' + gradeArray[index] + ',K线, T:' + startPosition + ',H:' + perGradeKlineChartHight);
            grids.push({
                show: true,
                left: '3%',
                right: '1%',
                height: perGradeKlineChartHight + '%',
                top: startPosition + '%',
                borderWidth: 1,
                backgroundColor: 'transparent'
            });

            var tmpSeriesObj = {
                name: gradeArray[index] + '-K线',
                type: 'candlestick',
                xAxisIndex: gridCount,
                yAxisIndex: gridCount,
                data: klineDataArray[index].datas,
                barWidth: '50%',
                large: true,
                largeThreshold: 400,//屏幕内展示小于400条， 用大K线展示
                progressive: 400,
                progressiveThreshold: 800,
                progressiveChunkMode: 'mod',
                emphasis: { disabled: true },
                itemStyle: {
                    color: me.upColor,
                    color0: me.downColor,
                    borderColor: me.upBorderColor,
                    borderColor0: me.downBorderColor
                }
            };
            var markPointData = [
                /*
                {
                    label: { position: 'top' },
                    symbol: 'pin',
                    symbolSize: [0, 0],
                    valueDim: 'highest',
                    type: 'max'
                },
                {
                    label: { position: 'bottom' },
                    symbol: 'pin',
                    symbolSize: [0, 0],
                    valueDim: 'lowest',
                    type: 'min'
                }*/
            ];
            var httpKlineData = myRawDatasMap.get(gradeArray[index]);
            if (httpKlineData.markPoint) {
                Array.prototype.push.apply(markPointData, httpKlineData.markPoint);
                //markPointData.push(...httpKlineData.markPoint);
            }
            tmpSeriesObj.markPoint = {
                //symbol: 'path://M38.52 62.5L1.02 62.5L59.52 137.5L118.02 62.5L81.52 62.5L81.52 0.5L38.52 0.5L38.52 62.5Z',
                symbol: 'pin',
                symbolSize: [20, 20],
                data: markPointData
            }
            if (httpKlineData.markLine) {
                tmpSeriesObj.markLine = {
                    label: {
                        position: 'middle',
                        textStyle: { color: '#FFFFFF', fontSize: 10 }
                    },
                    symbol: ['none', 'none'],
                    data: httpKlineData.markLine
                }
            }
            if (httpKlineData.markArea) {
                tmpSeriesObj.markArea = {
                    //silent: true,
                    itemStyle: {
                        color: 'rgb(160,160,160,0.4)'//'transparent',
                        //borderWidth: 1,
                        //borderType: 'dashed'
                    },
                    data: httpKlineData.markArea
                }
            }

            series.push(tmpSeriesObj);
            xAxes.push({
                type: 'category',
                gridIndex: gridCount,
                data: klineDataArray[index].times,
                scale: true,
                boundaryGap: true,
                axisLine: { onZero: true },
                axisLabel: { show: false, color: '#9b9da9', fontSize: 10 },
                splitLine: { show: false, lineStyle: { color: '#3a3a3e' } },
                splitNumber: 10,
                min: 'dataMin',
                max: 'dataMax',
                axisLabel: { color: '#9b9da9', fontSize: 10, show: !isMacdDisplayed },
                axisPointer: {
                    label: {
                        show: !isMacdDisplayed
                        /*formatter: function (params) {
                            var seriesValue = (params.seriesData[0] || {}).value;
                            return ((seriesValue != null ? echarts.format.addCommas(seriesValue) + '\n' : '') + params.value);
                        }*/
                    }
                }
            });
            yAxes.push({
                z: 2,
                gridIndex: gridCount,
                splitNumber: 3,
                scale: true,
                axisLabel: { color: '#c7c7c7', inside: false },
                splitLine: {
                    show: true,
                    lineStyle: {
                        color: '#3a3a3e'
                    }
                },
                splitArea: { show: false }
            });
            xAxisIndexArray.push(gridCount);
            gridCount = gridCount + 1;
            startPosition = Number(startPosition) + Number(perGradeKlineChartHight);
            if (isMacdDisplayed) {
                startPosition = Number(startPosition) + 1;
                console.log('级别：' + gradeArray[index] + ',M线, T:' + startPosition + ',H:' + perGradeMACDChartHight);
                grids.push({
                    show: true,
                    left: '3%',
                    right: '1%',
                    top: startPosition + '%',
                    height: perGradeMACDChartHight + '%',
                    borderWidth: 0,
                    backgroundColor: 'rgba(128, 128, 128, 0.1)'
                });
                series.push({
                    name: gradeArray[index] + '-MACD',
                    type: 'bar',
                    xAxisIndex: gridCount,
                    yAxisIndex: gridCount,
                    data: klineDataArray[index].macd,
                    barWidth: '5%',
                    itemStyle: {
                        color: function (params) { return params.data >= 0 ? me.upBorderColor : me.downColor; }
                    }
                }, {
                    name: gradeArray[index] + '-DIF',
                    type: 'line',
                    symbol: 'none',
                    xAxisIndex: gridCount,
                    yAxisIndex: gridCount,
                    data: klineDataArray[index].dif,
                    lineStyle: { color: '#da6ee8', width: 1 }
                }, {
                    name: gradeArray[index] + '-DEA',
                    type: 'line',
                    symbol: 'none',
                    xAxisIndex: gridCount,
                    yAxisIndex: gridCount,
                    data: klineDataArray[index].dea,
                    lineStyle: { opacity: 0.8, color: '#39afe6', width: 1 }
                });
                xAxes.push({
                    type: 'category',
                    gridIndex: gridCount,
                    data: klineDataArray[index].times,
                    axisLabel: { color: '#9b9da9', fontSize: 10, show: true },
                    axisPointer: {
                        label: {
                            show: true
                            /*formatter: function (params) {
                                var seriesValue = (params.seriesData[0] || {}).value;
                                return ((seriesValue != null ? echarts.format.addCommas(seriesValue) + '\n' : '') + params.value);
                            }*/
                        }
                    }
                });
                yAxes.push({
                    z: 2,
                    gridIndex: gridCount,
                    axisTick: { show: false },
                    axisLabel: { show: false },
                    axisLine: { show: false },
                    axisTick: { show: false },
                    splitLine: { show: false },
                    axisLabel: {
                        show: true,
                        color: '#c7c7c7',
                        inside: false,
                        fontSize: 8
                    }
                });
                xAxisIndexArray.push(gridCount);
                gridCount = gridCount + 1;
                startPosition = Number(startPosition) + Number(perGradeMACDChartHight);
            }
            startPosition = Number(startPosition) + 3;
        }
        console.log('startPosition:', startPosition, ',gridCount:', gridCount);

        option = {
            animation: false, //禁止动画效果
            backgroundColor: me.bgColor,
            blendMode: 'source-over', //'lighter', //'source-over',
            //color: [this.ma5Color, this.ma10Color, this.ma20Color, this.ma30Color],
            legend: { //左上角的图例控件,点击图例，可以控制哪些数据不显示
                // icon: 'rect',
                itemGap: 20,
                itemWidth: 18,
                itemHeight: 10,
                left: 0,
                top: '0.5%',
                textStyle: { fontSize: 12, color: '#c7c7c7' }
            },
            tooltip: {
                show: true,
                trigger: 'axis', //axis 或 item
                axisPointer: { type: 'cross' },
                borderWidth: 1,
                borderColor: '#ccc',
                backgroundColor: 'rgba(50,50,50,0.6)',
                padding: 10,
                textStyle: { color: '#c7c7c7' },
                position: function (pos, params, el, elRect, size) {
                    // const obj = { top: '5%' };
                    // obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 5)]] = '3%';
                    // return obj;
                    return (pos[0] < size.viewSize[0] / 5) ? { top: '5%', 'right': '1%' } : { top: '5%', 'left': '3%' }
                },
                // formatter: '{b0}: {c0}<br />{b1}: {c1}'
                // formatter: '<div style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background-color: rgb(48, 191, 120)"></div> {a}: {c}<br/>'
                //     + '<div style="display: inline-block; width: 10px; height: 10px; border-radius: 50%; background-color: rgb(244, 102, 74)"></div> {a1}: {c1}',
                formatter: function (params) {
                    var gradeKeyArray = ['M01', 'M05', 'M30', 'DAY'];
                    var myGradeMap = new Map();
                    for (var idx in params) {
                        var arr = params[idx].seriesName.split('-');
                        if (myGradeMap.has(arr[0])) {
                            var gradeParamsMap = myGradeMap.get(arr[0]);
                            gradeParamsMap.set(arr[1], params[idx]);
                        } else {
                            var gradeParamsMap = new Map();
                            gradeParamsMap.set(arr[1], params[idx]);
                            myGradeMap.set(arr[0], gradeParamsMap);
                        }
                    }
                    //axisIndex: 0, color:
                    var rtnTips = [];
                    rtnTips.push('<div style="margin: 0px 0 0;line-height:1;">');
                    var gridIndex = 0;
                    for (var idx in gradeKeyArray) {
                        if (myGradeMap.has(gradeKeyArray[idx])) {
                            var gradeParamsMap = myGradeMap.get(gradeKeyArray[idx]);
                            if (gradeParamsMap.has('K线')) {
                                var param = gradeParamsMap.get('K线');
                                rtnTips.push('<div style="margin: ' + (gridIndex == 0 ? '0' : '15') + 'px 0 0;line-height:1;">');
                                rtnTips.push('  <div style="margin: 0px 0 0;line-height:1;">');
                                rtnTips.push('      <span style="font-size:14px;color:#dfdfdf;font-weight:800;line-height:1;">' + gradeKeyArray[idx] + '</span>');
                                rtnTips.push('      <span style="float:right;font-size:14px;color:#c7c7c7;font-weight:400;line-height:1;">' + param.name + '</span>');
                                rtnTips.push('      <span><hr size=1 style="margin: 3px 0"></span>');
                                rtnTips.push('      <div style="clear:both"></div></div>');
                                //K线层
                                rtnTips.push('      <div style="margin: 0px 0 0;line-height:1;">');
                                rtnTips.push('          <div style="margin: 5px 0 0;line-height:1;">');
                                rtnTips.push('              <div style="margin: 5px 0 0;line-height:1;">');
                                rtnTips.push('                  <span style="display:inline-block;margin-right:4px;border-radius:8px;width:8px;height:8px;background-color:' + param.color + ';"></span>');
                                rtnTips.push('                  <span style="font-size:12px;color:#c7c7c7;font-weight:400;margin-left:2px">K线</span>');//param.seriesName
                                rtnTips.push('                  <span style="float:right;margin-left:20px;font-size:12px;color:#c7c7c7;font-weight:900"></span>');
                                rtnTips.push('              <div style="clear:both"></div>');
                                rtnTips.push('          </div>');
                                rtnTips.push('          <div style="margin: 5px 0 0;line-height:1;">');
                                rtnTips.push('              <span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;border-radius:4px;width:4px;height:4px;background-color:' + param.color + ';"></span>');
                                rtnTips.push('              <span style="font-size:12px;color:#c7c7c7;font-weight:400;margin-left:2px">开</span>');
                                rtnTips.push('              <span style="float:right;margin-left:20px;font-size:12px;color:#c7c7c7;font-weight:900">' + (param.value[param.encode.y[0]] == null ? '' : param.value[param.encode.y[0]].toFixed(2)) + '</span>');
                                rtnTips.push('              <div style="clear:both"></div>');
                                rtnTips.push('          </div>');
                                rtnTips.push('          <div style="margin: 5px 0 0;line-height:1;">');
                                rtnTips.push('              <span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;border-radius:4px;width:4px;height:4px;background-color:' + param.color + ';"></span>');
                                rtnTips.push('              <span style="font-size:12px;color:#c7c7c7;font-weight:400;margin-left:2px">收</span>');
                                rtnTips.push('              <span style="float:right;margin-left:20px;font-size:12px;color:#c7c7c7;font-weight:900">' + (param.value[param.encode.y[1]] == null ? '' : param.value[param.encode.y[1]].toFixed(2)) + '</span>');
                                rtnTips.push('              <div style="clear:both"></div>');
                                rtnTips.push('          </div>');
                                rtnTips.push('          <div style="margin: 5px 0 0;line-height:1;">');
                                rtnTips.push('              <span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;border-radius:4px;width:4px;height:4px;background-color:' + param.color + ';"></span>');
                                rtnTips.push('              <span style="font-size:12px;color:#c7c7c7;font-weight:400;margin-left:2px">高</span>');
                                rtnTips.push('              <span style="float:right;margin-left:20px;font-size:12px;color:#c7c7c7;font-weight:900">' + (param.value[param.encode.y[3]] == null ? '' : param.value[param.encode.y[3]].toFixed(2)) + '</span>');
                                rtnTips.push('              <div style="clear:both"></div>');
                                rtnTips.push('          </div>');
                                rtnTips.push('          <div style="margin: 5px 0 0;line-height:1;">');
                                rtnTips.push('              <span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;border-radius:4px;width:4px;height:4px;background-color:' + param.color + ';"></span>');
                                rtnTips.push('              <span style="font-size:12px;color:#c7c7c7;font-weight:400;margin-left:2px">低</span>');
                                rtnTips.push('              <span style="float:right;margin-left:20px;font-size:12px;color:#c7c7c7;font-weight:900">' + (param.value[param.encode.y[2]] == null ? '' : param.value[param.encode.y[2]].toFixed(2)) + '</span>');
                                rtnTips.push('              <div style="clear:both"></div>');
                                rtnTips.push('          </div>');
                                rtnTips.push('      <div style="clear:both"></div></div>');
                            }
                            if (gradeParamsMap.has('MACD')) {
                                var param = gradeParamsMap.get('MACD');
                                rtnTips.push('      <div style="margin: 10px 0 0;line-height:1;">');
                                rtnTips.push('          <div style="margin: 0px 0 0;line-height:1;">');
                                rtnTips.push('              <span style="display:inline-block;margin-right:4px;border-radius:8px;width:8px;height:8px;background-color:' + param.color + ';"></span>');
                                rtnTips.push('              <span style="font-size:12px;color:#c7c7c7;font-weight:400;margin-left:2px">MACD</span>');
                                rtnTips.push('              <span style="float:right;margin-left:20px;font-size:12px;color:#c7c7c7;font-weight:900">' + param.value + '</span>');
                                rtnTips.push('          <div style="clear:both"></div></div>');
                                rtnTips.push('      <div style="clear:both"></div></div>');
                            }
                            if (gradeParamsMap.has('DIF')) {
                                var param = gradeParamsMap.get('DIF');
                                rtnTips.push('      <div style="margin: 5px 0 0;line-height:1;">');
                                rtnTips.push('          <div style="margin: 0px 0 0;line-height:1;">');
                                rtnTips.push('              <span style="display:inline-block;margin-right:4px;border-radius:8px;width:8px;height:8px;background-color:transparent;"></span>');
                                rtnTips.push('              <span style="font-size:12px;color:#c7c7c7;font-weight:400;margin-left:2px">DIF</span>');
                                rtnTips.push('              <span style="float:right;margin-left:20px;font-size:12px;color:#c7c7c7;font-weight:900">' + param.value + '</span>');
                                rtnTips.push('          <div style="clear:both"></div></div>');
                                rtnTips.push('       <div style="clear:both"></div></div>');
                            }
                            if (gradeParamsMap.has('DEA')) {
                                var param = gradeParamsMap.get('DEA');
                                rtnTips.push('      <div style="margin: 5px 0 0;line-height:1;">');
                                rtnTips.push('          <div style="margin: 0px 0 0;line-height:1;"><span');
                                rtnTips.push('              <span style="display:inline-block;margin-right:4px;border-radius:8px;width:8px;height:8px;background-color:transparent;"></span>');
                                rtnTips.push('              <span style="font-size:12px;color:#c7c7c7;font-weight:400;margin-left:2px">DEA</span>');
                                rtnTips.push('              <span style="float:right;margin-left:20px;font-size:12px;color:#c7c7c7;font-weight:900">' + param.value + '</span>');
                                rtnTips.push('          <div style="clear:both"></div></div>');
                                rtnTips.push('      <div style="clear:both"></div></div>');
                            }
                            rtnTips.push('  <div style="clear:both"></div></div>');
                            rtnTips.push('<div style="clear:both"></div></div>');
                            gridIndex = gridIndex + 1;
                        }
                    }
                    rtnTips.push('<div style="clear:both"></div></div>');
                    return rtnTips.join('');
                },
                extraCssText: 'width: 200px'
            },
            axisPointer: {
                show: true,
                link: [{ xAxisIndex: 'all' }],
                label: { show: true, color: '#FFFFFF', backgroundColor: '#777' }
            },
            dataZoom: [
                {
                    type: 'inside',
                    xAxisIndex: xAxisIndexArray,
                    start: 80,
                    end: 100
                },
                {
                    type: 'slider',
                    xAxisIndex: xAxisIndexArray, //控件联动
                    start: 80,
                    end: 100,
                    throttle: 100, //设置触发视图刷新的频率。单位为毫秒（ms）。
                    top: '95%',
                    height: '5%',
                    borderColor: '#696969',
                    textStyle: { color: '#dcdcdc' },
                    realtime: true,
                    dataBackground: {
                        lineStyle: { color: '#fff' },
                        areaStyle: { color: '#696969' }
                    }
                }
            ],
            title: [
                {
                    text: title,
                    left: 'right',
                    textStyle: { fontSize: 22, color: 'white' }
                }
            ],
            grid: grids,
            xAxis: xAxes,
            yAxis: yAxes,
            series: series
        };
        return option;
    },
    /**
     * 数组处理
     */
    splitData: function (rawData, isMacdDisplayed) {
        var datas = [];
        var times = [];
        var vols = [];
        var macd = [];
        var dif = [];
        var dea = [];
        if (local_ajax) {
            for (var i = 0; i < rawData.length; i++) {
                datas.push(rawData[i]);
                times.push(rawData[i].splice(0, 1)[0]);
                vols.push(rawData[i].splice(4, 1)[0]);
            }
        } else {
            for (var i = 0; i < rawData.length; i++) {
                datas.push(rawData[i]);
                times.push(rawData[i].value.splice(0, 1)[0]);
                vols.push(rawData[i].value.splice(4, 1)[0]);
                if (isMacdDisplayed && rawData[i].value.length == 7) {
                    macd.push(rawData[i].value.splice(4, 1)[0]);
                    dif.push(rawData[i].value.splice(4, 1)[0]);
                    dea.push(rawData[i].value.splice(4, 1)[0]);
                }
            }
        }

        return { datas: datas, times: times, vols: vols, macd: macd, dif: dif, dea: dea };
    },

    /**
     * MA计算
     */
    calculateMA: function (dayCount, data) {
        var result = [];
        for (var i = 0, len = data.times.length; i < len; i++) {
            if (i < dayCount) {
                result.push('-');
                continue;
            }
            var sum = 0;
            for (var j = 0; j < dayCount; j++) {
                sum += data.datas[i - j][1];
            }
            result.push((sum / dayCount).toFixed(2));
        }
        return result;
    },

    /**
     * 精确的四舍五入 
     */
    roundNumber: function (number, decimals) {
        const factor = 10 * decimals;
        return Math.round(number * factor) / factor;
    },

    /**
     * 失去焦点, trim文本及校验slimsymbol是否有效
     */
    verifySlimsymbol: function (myviewmodel, slimsymbol) {
        re = /^(([s]{1}[z]{1}[30]{1})|([s]{1}[h]{1}[6]{1}))(\d{5})$/ //匹配股票代码正则表达式 
        if (re.test(slimsymbol)) {
            Ext.Ajax.request({
                url: BizHttpAction.queryStockBySlimSymbol.url + '/' + slimsymbol,
                method: BizHttpAction.queryStockBySlimSymbol.method,
                async: false,
                success: function (response, opts) {
                    var respJson = Ext.JSON.decode(response.responseText);
                    if (respJson.success != true) {
                        throw new Error(respJson.message)
                    }
                    var stkName = respJson.data.name;

                    myviewmodel.set('isValidSlimsymbol', true);
                    myviewmodel.set('slimsymbol', slimsymbol);
                    myviewmodel.set('stkname', stkName);

                },
                failure: function (response, opts) {
                    var failureMsg;
                    if (!Ext.String.startsWith(response.getResponseHeader("Content-type"), "application/json", true)) {
                        failureMsg = 'HTTP请求异常, 状态:' + response.status
                    } else {
                        var respJson = Ext.JSON.decode(response.responseText);
                        failureMsg = respJson.message;
                    }
                    myviewmodel.set('isValidSlimsymbol', false);
                    alert(failureMsg);
                }
            });
        } else {
            alert('不匹配股票代码正则表达式' + slimsymbol);
            myviewmodel.set('isValidSlimsymbol', false);

        }
    }
});

// Ext.EventManager.onWindowResize(function(){
//     Ext.ComponentManager.each(function(cmpId,cmp,length){
//     	if(cmp.hasOwnProperty("renderTo")){
//     		cmp.doLayout();
//         }
//     });
// });
